package com.slaffka.dao;

import com.slaffka.model.User;
import org.jboss.solder.logging.Logger;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import java.io.Serializable;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: slaffka
 * Date: 18.11.12
 * Time: 22:32
 * To change this template use File | Settings | File Templates.
 */
@Singleton
public class UserDAO implements Serializable {
    @PersistenceContext
    EntityManager entityManager;

    @Inject
    private Logger log;

    private List<User> allUsers;

    public List<User> getAllUsers(){
        if (allUsers == null){
            allUsers = entityManager
                    .createQuery("select u from User u")
                    .getResultList();
        }
        return allUsers;
    }

    public User getUserByUsername(String username){
        User user = null;
        if (username == null || username.isEmpty()){
            return user;
        }
        try {
            user = (User) entityManager
                    .createQuery("select u from User u where u.username = :username")
                    .setParameter("username", username)
                    .getSingleResult();
        } catch (NonUniqueResultException e){
            log.error("найдено более одной записи user по username = " + username);
            e.printStackTrace();
        } catch (NoResultException e){
            log.error("на найдено записей user по username = " + username);
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }
}
